/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ronsicecream.pos.wh.transaction.posupplier;

import com.buanalintas.bynga.Access;
import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.ronsicecream.pos.entities.PosMasterPriceMainkitchen;
import com.ronsicecream.pos.entities.PosMasterPriceWarehouse;
import com.ronsicecream.pos.entities.PosMasterUnit;
import com.ronsicecream.pos.entities.PosTransactionHoPurchaseOrderSupplier;
import com.ronsicecream.pos.entities.PosTransactionHoPurchaseOrderSupplierDetail;
import com.ronsicecream.pos.wh.transaction.posupplierdetail.PurchaseOrderSupplierDetail;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;

/**
 *
 * @author user
 */
public class PurchaseOrderSupplier extends Page {

    private Field purchaseOrderId;
    private Field purchaseOrderNumber;
    private Field purchaseOrderDate;
    private Field purchaseOrderStatus;
    private Field purchaseOrderKeel;
    private Field purchaseOrderTotal;
    private Field purchaseOrderQuantity;
    private Field purchaseOrderPaid;
    private Field purchaseOrderReceived;
    private Field purchaseOrderUnreceived;
    private Field purchaseOrderProgress;
    private Field purchaseOrderRejectReason;
    private Field purchaseOrderDescription;
    private Field purchaseOrderTimestamp;
    private Field purchaseOrderRegionalId;
    private Field purchaseOrderSupplierId;
    private Field purchaseOrderPosUnitId;
    private Field purchaseOrderUnitId;
    private Field purchaseOrderUserId;
    private Action actionRevision = new Action("revisi", "Revision Request");
    private Action actionReject = new Action("reject", "Reject Request");
    private Action actionAgree = new Action("approve", "Agree Request");

    public PurchaseOrderSupplier() {
        super();

        setTheClass(PosTransactionHoPurchaseOrderSupplier.class);

        setPageDetail(PurchaseOrderSupplierDetail.class);


        purchaseOrderId = new Field();
        purchaseOrderId.setName("purchaseOrderId");
        purchaseOrderId.setCaption("id");
        //purchaseOrderId.setInfo("purchase order id");
        purchaseOrderId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        purchaseOrderId.setInputProperties(" size=\"20\"");
        getFields().add(purchaseOrderId);

        purchaseOrderNumber = new Field();
        purchaseOrderNumber.setName("purchaseOrderNumber");
        purchaseOrderNumber.setCaption("number");
        purchaseOrderNumber.setRequired(true);
        purchaseOrderNumber.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        purchaseOrderNumber.setInputProperties(" size=\"30\" readonly");
        getFields().add(purchaseOrderNumber);

        purchaseOrderDate = new Field();
        purchaseOrderDate.setName("purchaseOrderDate");
        purchaseOrderDate.setCaption("date");
        purchaseOrderDate.setRequired(true);
        purchaseOrderDate.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        purchaseOrderDate.setInputProperties(" size=\"8\"");
        purchaseOrderDate.setDefaultValue(Utility.getTimestamp());
        getFields().add(purchaseOrderDate);

        purchaseOrderRejectReason = new Field();
        purchaseOrderRejectReason.setName("purchaseOrderRejectReason");
        purchaseOrderRejectReason.setCaption("Reject Reason");
        //purchaseOrderStatus.setInfo("purchase order status");
        purchaseOrderRejectReason.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        purchaseOrderRejectReason.setInputProperties(" size=\"20\"");
        getFields().add(purchaseOrderRejectReason);

//        purchaseOrderKeel = new Field();
//        purchaseOrderKeel.setName("purchaseOrderKeel");
//        purchaseOrderKeel.setCaption("keel");
//        //purchaseOrderKeel.setInfo("purchase order keel");
//        purchaseOrderKeel.setListProperties(" align=\"left\" width=\"5%\" nowrap");
//        purchaseOrderKeel.getOptions().add(new String[]{"1", " No"});
//        purchaseOrderKeel.getOptions().add(new String[]{"2", " Yes"});
//        getFields().add(purchaseOrderKeel);

        purchaseOrderTotal = new Field();
        purchaseOrderTotal.setName("purchaseOrderTotal");
        purchaseOrderTotal.setCaption("total");
        //purchaseOrderTotal.setInfo("purchase order total");
        purchaseOrderTotal.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        purchaseOrderTotal.setInputProperties(" size=\"20\"");
        getFields().add(purchaseOrderTotal);

        purchaseOrderQuantity = new Field();
        purchaseOrderQuantity.setName("purchaseOrderQuantity");
        purchaseOrderQuantity.setCaption("Quantity");
        //purchaseOrderQuantity.setInfo("purchase order total");
        purchaseOrderQuantity.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        purchaseOrderQuantity.setInputProperties(" size=\"20\"");
        getFields().add(purchaseOrderQuantity);

//        purchaseOrderPaid = new Field();
//        purchaseOrderPaid.setName("purchaseOrderPaid");
//        purchaseOrderPaid.setCaption("paid");
//        //purchaseOrderPaid.setInfo("purchase order paid");
//        purchaseOrderPaid.setListProperties(" align=\"left\" width=\"10%\" nowrap");
//        purchaseOrderPaid.setInputProperties(" size=\"20\"");
//        getFields().add(purchaseOrderPaid);

        purchaseOrderReceived = new Field();
        purchaseOrderReceived.setName("purchaseOrderReceived");
        purchaseOrderReceived.setCaption("received");
        //purchaseOrderReceived.setInfo("purchase order received");
        purchaseOrderReceived.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        purchaseOrderReceived.setInputProperties(" size=\"20\"");
        getFields().add(purchaseOrderReceived);

        purchaseOrderUnreceived = new Field();
        purchaseOrderUnreceived.setName("purchaseOrderUnreceived");
        purchaseOrderUnreceived.setCaption("unreceived");
        //purchaseOrderUnreceived.setInfo("purchase order unreceived");
        purchaseOrderUnreceived.setListProperties(" align=\"left\" width=\"5%\" nowrap");
        purchaseOrderUnreceived.setInputProperties(" size=\"20\"");
        getFields().add(purchaseOrderUnreceived);

        purchaseOrderProgress = new Field();
        purchaseOrderProgress.setName("purchaseOrderProgress");
        purchaseOrderProgress.setCaption("progress");
        //purchaseOrderProgress.setInfo("purchase order progress");
        purchaseOrderProgress.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        purchaseOrderProgress.getOptions().add(new String[]{"1", "NEW"});
        purchaseOrderProgress.getOptions().add(new String[]{"2", "REJECT"});
        purchaseOrderProgress.getOptions().add(new String[]{"3", "REVISION"});
        purchaseOrderProgress.getOptions().add(new String[]{"4", "APPROVED"});
        getFields().add(purchaseOrderProgress);

        purchaseOrderDescription = new Field();
        purchaseOrderDescription.setName("purchaseOrderDescription");
        purchaseOrderDescription.setCaption("description");
        //purchaseOrderDescription.setInfo("purchase order description");
        purchaseOrderDescription.setListProperties(" align=\"left\" width=\"25%\" nowrap");
        purchaseOrderDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        purchaseOrderDescription.setInputType(Field.INPUT_TEXT_AREA);
        purchaseOrderDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(purchaseOrderDescription);

        purchaseOrderTimestamp = new Field();
        purchaseOrderTimestamp.setName("purchaseOrderTimestamp");
        purchaseOrderTimestamp.setCaption("timestamp");
        //purchaseOrderTimestamp.setInfo("purchase order timestamp");
        purchaseOrderTimestamp.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        purchaseOrderTimestamp.setInputProperties(" size=\"12\"");
//        purchaseOrderTimestamp.setFormatter(DateFormatter.getInstanceDateTime(this));
        getFields().add(purchaseOrderTimestamp);

        purchaseOrderRegionalId = new Field();
        purchaseOrderRegionalId.setName("purchaseOrderRegionalId");
        purchaseOrderRegionalId.setCaption("regional");
        purchaseOrderRegionalId.setRequired(true);
        purchaseOrderRegionalId.setListProperties(" align=\"left\" width=\"10%\" nowrap");
        purchaseOrderRegionalId.setInputType(Field.INPUT_COMBO_BOX);
        getFields().add(purchaseOrderRegionalId);

        purchaseOrderSupplierId = new Field();
        purchaseOrderSupplierId.setName("purchaseOrderSupplierId");
        purchaseOrderSupplierId.setCaption("supplier");
        purchaseOrderSupplierId.setRequired(true);
        purchaseOrderSupplierId.setListProperties(" align=\"left\" width=\"15%\" nowrap");
        purchaseOrderSupplierId.setInputProperties(" size=\"20\"");
        purchaseOrderSupplierId.getSelectorColumns().add(new String[]{"supplierCode", " Code", "width=\"30%\" nowrap"});
        purchaseOrderSupplierId.getSelectorColumns().add(new String[]{"supplierName", " Name", "width=\"50%\""});
        purchaseOrderSupplierId.getSelectorColumns().add(new String[]{"supplierPhone", " Phone", "align=\"center\" width=\"20%\" nowrap"});
        getFields().add(purchaseOrderSupplierId);

        purchaseOrderUnitId = new Field();
        purchaseOrderUnitId.setName("purchaseOrderUnitId");
        purchaseOrderUnitId.setCaption("Unit");
        //purchaseOrderUnitId.setInfo("pos master supplier");
        purchaseOrderUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        purchaseOrderUnitId.setInputProperties(" size=\"20\"");
        getFields().add(purchaseOrderUnitId);

        purchaseOrderPosUnitId = new Field();
        purchaseOrderPosUnitId.setName("purchaseOrderPosUnitId");
        purchaseOrderPosUnitId.setCaption("Pos Unit");
        //purchaseOrderUnitId.setInfo("pos master supplier");
        purchaseOrderPosUnitId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        purchaseOrderPosUnitId.setInputProperties(" size=\"20\"");
        getFields().add(purchaseOrderPosUnitId);

        purchaseOrderUserId = new Field();
        purchaseOrderUserId.setName("purchaseOrderUserId");
        purchaseOrderUnitId.setCaption("User");
        //purchaseOrderUnitId.setInfo("pos master supplier");
        purchaseOrderUserId.setListProperties(" align=\"left\" width=\"1%\" nowrap");
        purchaseOrderUserId.setInputProperties(" size=\"20\"");
        getFields().add(purchaseOrderUserId);

        fillFields();

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        getFieldsAdd().clear();
        getFieldsAdd().add(purchaseOrderDate);
        getFieldsAdd().add(purchaseOrderNumber);
        getFieldsAdd().add(purchaseOrderSupplierId);
//        getFieldsAdd().add(purchaseOrderRegionalId);
        getFieldsAdd().add(purchaseOrderDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(purchaseOrderDate);
        getFieldsEdit().add(purchaseOrderNumber);
        getFieldsEdit().add(purchaseOrderSupplierId);
//        getFieldsEdit().add(purchaseOrderRegionalId);
        getFieldsEdit().add(purchaseOrderDescription);

        getFieldsList().clear();
        getFieldsList().add(purchaseOrderNumber);
        getFieldsList().add(purchaseOrderDate);
        getFieldsList().add(purchaseOrderSupplierId);
        getFieldsList().add(purchaseOrderRegionalId);
        getFieldsList().add(purchaseOrderRejectReason);
        getFieldsList().add(purchaseOrderProgress);
        getFieldsList().add(purchaseOrderQuantity);
        getFieldsList().add(purchaseOrderReceived);
        getFieldsList().add(purchaseOrderTotal);
        getFieldsList().add(purchaseOrderDescription);

        getFieldsView().clear();
        getFieldsView().add(purchaseOrderDate);
        getFieldsView().add(purchaseOrderNumber);
        getFieldsView().add(purchaseOrderSupplierId);
        getFieldsView().add(purchaseOrderRegionalId);
        getFieldsView().add(purchaseOrderPosUnitId);
        getFieldsView().add(purchaseOrderRejectReason);
        getFieldsView().add(purchaseOrderQuantity);
        getFieldsView().add(purchaseOrderReceived);
        getFieldsView().add(purchaseOrderUnreceived);
        getFieldsView().add(purchaseOrderTotal);
        getFieldsView().add(purchaseOrderPaid);
        getFieldsView().add(purchaseOrderKeel);
        getFieldsView().add(purchaseOrderProgress);
        getFieldsView().add(purchaseOrderDescription);
        getFieldsView().add(purchaseOrderUserId);
        getFieldsView().add(purchaseOrderUnitId);
        getFieldsView().add(purchaseOrderTimestamp);

        getFieldsAdd().remove(purchaseOrderId);
        getFieldsEdit().remove(purchaseOrderId);
        getFieldsList().remove(purchaseOrderId);
        getFieldsView().remove(purchaseOrderId);

        getActions().add(actionAgree);
        getActions().add(actionReject);


        setExportList(getClass().getResourceAsStream("PurchaseOrderList.jasper"));
        setExport(getClass().getResourceAsStream("PurchaseOrder.jasper"));




        setController(new Controller(this) {
            @Override
            public void beforeInsert(Object data, List list) {
                PosTransactionHoPurchaseOrderSupplier po = (PosTransactionHoPurchaseOrderSupplier) data;
                System.out.println("jose :" + po);
                EntityManager em = getEntityManager();
                po.setPurchaseOrderNumber(generate());
                po.setPurchaseOrderUnitId(getCurrentUnit());
                po.setPurchaseOrderUserId(getCurrentUser());
                po.setPurchaseOrderTimestamp(Utility.getTimestamp());
                po.setPurchaseOrderDate(Utility.getTimestamp());
                po.setPurchaseOrderStatus("1");
                po.setPurchaseOrderProgress("1");
//                PosMasterRegional regional = (PosMasterRegional) em.createQuery("SELECT t FROM PosMasterRegional t "
//                        + " WHERE t.regionalId=1").setHint(Persistence.REFRESH_HINT, true).getSingleResult();
//                System.out.println("Cek Regional " + regional);
//                po.setPurchaseOrderRegionalId(regional);
                po.setPurchaseOrderReceived(BigDecimal.ZERO);

                PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
                        + " WHERE t.unitUnitTypeId.unitTypeId=6 "
                        + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId() 
                        )
                        .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
                po.setPurchaseOrderPosUnitId(posunit);
                po.setPurchaseOrderRegionalId(posunit.getUnitRegionalId());
                System.out.println("Regional : " + posunit);
                BigDecimal test = BigDecimal.ZERO;
                BigDecimal qty = BigDecimal.ZERO;
                for (int i = 0; i < list.size(); i++) {
                    List<PosTransactionHoPurchaseOrderSupplierDetail> poDetails = list;
                    
                     PosMasterPriceWarehouse price = (PosMasterPriceWarehouse) em.createQuery("SELECT t FROM PosMasterPriceWarehouse t"
                        + " WHERE t.pricePosUnitId.unitId="+posunit.getUnitId()
                        + " AND t.priceItemId.itemId=" + poDetails.get(i).getPurchaseOrderDetailItemId().getItemId()
//                        + " AND t.unitRegionalId.regionalId=" + request.getRequestRegionalId().getRegionalId()
                        )
                        .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                     
                     price.setPricePrice(poDetails.get(i).getPurchaseOrderDetailPrice());
                    
                    poDetails.get(i).setPurchaseOrderDetailSent(BigDecimal.ZERO);
                    poDetails.get(i).setPurchaseOrderDetailUnsent(poDetails.get(i).getPurchaseOrderDetailQuantity());
                    test = test.add(poDetails.get(i).getPurchaseOrderDetailQuantity().multiply(poDetails.get(i).getPurchaseOrderDetailPrice()));
                    qty = qty.add(poDetails.get(i).getPurchaseOrderDetailQuantity());
                }
                po.setPurchaseOrderTotal(test);
                po.setPurchaseOrderUnreceived(qty);
                po.setPurchaseOrderQuantity(qty);
                po.setPurchaseOrderTotal(test);
            }

            @Override
            public void afterInsert(Object data, List list) {
                PosTransactionHoPurchaseOrderSupplier po = (PosTransactionHoPurchaseOrderSupplier) data;
                EntityManager em = getEntityManager();
                try {
                    PosMasterUnit posunit = (PosMasterUnit) em.createQuery("SELECT t FROM PosMasterUnit t"
                            + " WHERE t.unitUnitTypeId.unitTypeId=6 "
                            + " AND t.unitUnitId.unitId=" + getCurrentUnit().getUnitId() //                            + " AND t.unitRegionalId.regionalId=" + po.getPurchaseOrderRegionalId().getRegionalId()
                            )
                            .setHint(Persistence.REFRESH_HINT, true).getSingleResult();
                    System.out.println("unittt :" + posunit + " unit name: " + posunit.getUnitName());
                    po.setPurchaseOrderPosUnitId(posunit);
                    po.setPurchaseOrderRegionalId(posunit.getUnitRegionalId());
                    System.out.println("Regional : " + posunit);
                    
                   
                } catch (Exception e) {
                    System.out.println("Errororrr " + e);
                }
            }
        });
        getController().setOrder(purchaseOrderTimestamp);
        getController().setOrderType("DESC");
    }

    @Override
    public String addJavascript() {
        return "<script>function __revision(id) {var reason = prompt('" + Dictionary.getValue(this, "Enter revision reason") + "?', ''); if (reason != null) { location.href = \"?m=" + getMenu().getMenuName() + "&a=" + actionRevision.getName() + "&id=\"+id+\"&reason=\"+escape(reason); } return false; };function __reject(id) {var reason = prompt('" + Dictionary.getValue(this, "Enter rejected reason") + "?', ''); if (reason != null) { location.href = \"?m=" + getMenu().getMenuName() + "&a=" + actionReject.getName() + "&id=\"+id+\"&reason=\"+escape(reason); } return false; }</script>";
    }

    @Override
    public boolean isGranted(Action action, Object data) {
        boolean granted = super.isGranted(action, data);
        if (granted) {
            PosTransactionHoPurchaseOrderSupplier po = (PosTransactionHoPurchaseOrderSupplier) data;
            if (action.equals(Action.EDIT) || action.equals(Action.TRANS_EDIT) || action.equals(Action.DELETE)) {
                granted = po.getPurchaseOrderProgress() == null || po.getPurchaseOrderProgress().equals("1") || po.getPurchaseOrderProgress().equals("2");
            }
        }
        return granted;
    }

    @Override
    public String delete(Object data) {
        String delete = super.delete(data);
        if (delete == null) {
            PosTransactionHoPurchaseOrderSupplier po = (PosTransactionHoPurchaseOrderSupplier) data;
            if (!"1".equals(po.getPurchaseOrderProgress())) {
                delete = Dictionary.getValue(this, "can not be deleted");
            }
        }
        return delete;
    }

    @Override
    public StringBuffer processCustomRowCommand(StringBuffer template, Page page, Object data) {
        StringBuffer commands = new StringBuffer();
        StringBuffer command = null;
        PosTransactionHoPurchaseOrderSupplier po = (PosTransactionHoPurchaseOrderSupplier) data;
        if (po.getPurchaseOrderProgress() == null || po.getPurchaseOrderProgress().equals("1")) {
            if (Access.isGranted(page, actionRevision)) {
                command = new StringBuffer(template.toString());
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionRevision.getName() + "&id=" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Revision request"));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __revision('" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())) + "')\"");
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=command-revision.png");
                commands.append(command.toString());
            }
            if (Access.isGranted(page, actionReject)) {
                command = new StringBuffer(template.toString());
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionReject.getName() + "&id=" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Reject request"));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __reject('" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())) + "')\"");
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=command-reject.png");
                commands.append(command.toString());
            }
            if (Access.isGranted(page, actionAgree)) {
                command = new StringBuffer(template.toString());
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionAgree.getName() + "&id=" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Approve request"));
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return confirm('" + Dictionary.getValue(page, "Approve request") + "?')\"");
                Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=command-approve.png");
                commands.append(command.toString());
            }
        }
        return commands;
    }

    @Override
    public String doAction() {

        String id = Utility.decode(Utility.getParameter(getRequest(), "id"));
        if (id != null && !id.trim().equals("")) {
            PosTransactionHoPurchaseOrderSupplier data = (PosTransactionHoPurchaseOrderSupplier) getController().getData(id);
            if (getAction().equals(actionRevision)) {
                String reason = Utility.getParameter(getRequest(), "reason");
                if (reason == null || reason.trim().equals("")) {
                    return "err:" + Dictionary.getValue(this, "Please enter revision reason");
                }
                try {
                    data.setPurchaseOrderProgress("2");
                    data.setPurchaseOrderRejectReason(Utility.getParameter(getRequest(), "reason"));
                    getController().update(data);
                    return "ok:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected succesfully");
                } catch (Exception e) {
                    Logger.getInstance().log(e);
                    return "err:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected failed") + ": " + e.getMessage();
                }
            } else if (getAction().equals(actionReject)) {
                String reason = Utility.getParameter(getRequest(), "reason");
                if (reason == null || reason.trim().equals("")) {
                    return "err:" + Dictionary.getValue(this, "Please enter rejected reason");
                }
                try {
                    data.setPurchaseOrderProgress("3");
                    data.setPurchaseOrderRejectReason(Utility.getParameter(getRequest(), "reason"));
                    getController().update(data);
                    return "ok:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected succesfully");
                } catch (Exception e) {
                    Logger.getInstance().log(e);
                    return "err:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "rejected failed") + ": " + e.getMessage();
                }
            } else if (getAction().equals(actionAgree)) {

                try {
                    data.setPurchaseOrderProgress("4");
                    getController().update(data);
                    return "ok:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "approved succesfully");
                } catch (Exception e) {
                    Logger.getInstance().log(e);
                    return "err:" + Dictionary.getValue(this, "Data with") + " " + getObjectInfo(data) + " " + Dictionary.getValue(this, "approved failed") + ": " + e.getMessage();
                }
            }
        }
        return null;
    }

    @Override
    public void beforeAdd() {
        purchaseOrderNumber.setDefaultValue(generate());
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionHoPurchaseOrderSupplier po = (PosTransactionHoPurchaseOrderSupplier) getEntityManager().createQuery("SELECT t FROM PosTransactionHoPurchaseOrderSupplier t "
                    + "WHERE t.purchaseOrderNumber LIKE '%/" + unitCode + "/Rons/PO-Supplier/%/" + year + "' "
                    + "ORDER BY t.purchaseOrderTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(po.getPurchaseOrderNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/Rons/PO-Supplier/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/Rons/PO-Supplier/" + month + "/" + year;
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Purchase Order Supplier"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
